// 页面路径：store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
import {NumberUtils} from 'great-jsutils'
import moduleA from '@/store/modules/module-a'

Vue.use(Vuex);//vue的插件机制

//Vuex.Store 构造器选项
const store = new Vuex.Store({
    // 定义状态
    state:{//存放状态
        "leftActiveComponent":"vuex",// 当前左侧组件名称
        "username":"foo1",
        "age":18
    },
    // 获取状态
    getters: {
        usernamelen: state => {
            return state.username.length;
        },
        // 方法形式
        getByAttrName: (state)=>(attrName:string)=>{
            if(attrName==="username"){
                return state.username
            }else{
                return state.age;
            }
        }
    },
    // 修改状态，必须为同步
    mutations:{
        updateAge(state){
            state.age = NumberUtils.randomInt({max:100}) as number;
        },
        // 带参方法
        updateUsername(state, newName){
            state.username = newName;
        },
        // 参数为对象
        update(state, payload){
            state.username = payload.username;
            state.age = payload.age;
        },
        // 参数为对象
        update2(state, payload){
            state.username = payload.username;
            state.age = payload.age;
        },
        setLeftActiveComponent(state:any, tabPage:string) {
            state.leftActiveComponent = tabPage
        }
    },
    // 可以异步修改状态
    actions:{
        updateAge (context) {
            //在执行累加的时候，会等待两秒才执行
            setTimeout(function () {
                context.commit('updateAge')
            }, 2000)
        },
        // 带参方法
        updateUsername(context, newName){
            //在执行累加的时候，会等待两秒才执行
            setTimeout(function () {
                context.commit('updateUsername', newName);
            }, 2000)
        },
        // 支持回调，知道异步修改状态完成
        updateAgePromise ({ commit }) {
            return new Promise((resolve, reject) => {
                setTimeout(() => {
                    commit('updateAge')
                    resolve()
                }, 1000)
            })
        }
    },
    modules:{
        moduleA
    }
})
export default store
